package com.topcent.tioxyc.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.CustomerOrderSummaryMapper;
import com.topcent.tioxyc.mapper.DeliveryDocumentsMapper;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.CustomerOrderSummary;
import com.topcent.tioxyc.pojo.DeliveryDocuments;
import com.topcent.tioxyc.pojo.MonthlyCustomerStatistics;
import com.topcent.tioxyc.pojo.YY1_KPI;
import com.topcent.tioxyc.pojo.vo.CustomerStatistics;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: weidian
 * @date: 2024/10/10 14:27
 * @Description: DeliveryDocuments 外向交货单
 * <p>
 * 销售订单YY1 KPI
 */
@Slf4j
@RestController
public class OneTimeController {

    @Autowired
    private Yy1KpiMapper yy1KpiMapper;
    @Autowired
    private DeliveryDocumentsMapper deliveryDocumentsMapper;

    @Autowired
    private CustomerOrderSummaryMapper customerOrderSummaryMapper;

    @GetMapping("/KPL")
    public void YY_KPl() {
//        Header[] headers = new Header[3];
//        headers[0] = new BasicHeader("Accept", "application/json");
//        headers[1] = new BasicHeader("Authorization", "Basic " + KeyConstant.SAP01);
//        headers[2] = new BasicHeader("x-csrf-token", "Fetch");
//        JSONObject entries = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_SALESBOARD_CDS/YY1_SalesBoard", headers, null);
//        String d = entries.getStr("d");
//        JSONObject objects = JSONUtil.parseObj(d);
//        String results = objects.getStr("results");
//        JSONArray objectss = JSONUtil.parseArray(results);
//        List<YY1_KPI> yy1Kpis = JSONUtil.toList(objectss, YY1_KPI.class);
//        yy1KpiMapper.truncateTable();
//        for (YY1_KPI yy1Kpi : yy1Kpis) {
//            if (yy1Kpi.getYY1_lachangedatetime1_SDH() != null && !yy1Kpi.getYY1_lachangedatetime1_SDH().isBlank()) {
//                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(yy1Kpi.getYY1_lachangedatetime1_SDH()));
//                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
//                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
//                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
//                yy1Kpi.setYY1_lachangedatetime1_SDHs(dateTime4);
//            }
//            int i1 = yy1KpiMapper.insertSalesDocument(yy1Kpi);
//            if (i1 == 0) {
//                log.info("YY1_KPl插入失败，ID为{}", yy1Kpi.getID());
//            }
//        }

        Header[] headers1 = new Header[3];
        headers1[0] = new BasicHeader("Accept", "application/json");
        headers1[1] = new BasicHeader("Authorization", "Basic " + KeyConstant.SAP01);
        headers1[2] = new BasicHeader("x-csrf-token", "Fetch");
        JSONObject entries1 = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_DELIVERYDOCUMENT_API_CDS/YY1_DeliveryDocument_API", headers1, null);
        String d1 = entries1.getStr("d");
        JSONObject objects1 = JSONUtil.parseObj(d1);
        String results1 = objects1.getStr("results");
        JSONArray objectss1 = JSONUtil.parseArray(results1);
        List<DeliveryDocuments> deliveryDocuments = JSONUtil.toList(objectss1, DeliveryDocuments.class);
        deliveryDocumentsMapper.truncateTable();
        for (DeliveryDocuments deliveryDocuments1 : deliveryDocuments) {
            if (deliveryDocuments1.getCreationDate() != null && !deliveryDocuments1.getCreationDate().isBlank()) {
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(deliveryDocuments1.getCreationDate()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                deliveryDocuments1.setCreationDates(dateTime4);
            }
            if (deliveryDocuments1.getDocumentDate() != null && !deliveryDocuments1.getDocumentDate().isBlank()) {
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(deliveryDocuments1.getDocumentDate()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                deliveryDocuments1.setDocumentDates(dateTime4);
            }
            if (deliveryDocuments1.getActualGoodsMovementDate() != null && !deliveryDocuments1.getActualGoodsMovementDate().isBlank()) {
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(deliveryDocuments1.getActualGoodsMovementDate()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                deliveryDocuments1.setActualGoodsMovementDates(dateTime4);
            }
            if (deliveryDocuments1.getPlannedGoodsIssueDate() != null && !deliveryDocuments1.getPlannedGoodsIssueDate().isBlank()) {
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(deliveryDocuments1.getPlannedGoodsIssueDate()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                deliveryDocuments1.setPlannedGoodsIssueDates(dateTime4);
            }
            int i1 = deliveryDocumentsMapper.insertDeliveryDocument(deliveryDocuments1);
            if (i1 == 0) {
                log.info("DeliveryDocuments插入失败，ID为{}", deliveryDocuments1.getID());
            }

        }
    }




    @GetMapping("/OrderSummary")
    public String CustomerOrderSummary() {
        List<CustomerStatistics> customerStatistics = yy1KpiMapper.getCustomerStatistics();
        List<CustomerOrderSummary> customerOrderSummaries = new ArrayList<>();
        for (CustomerStatistics customerStatistic : customerStatistics) {
            CustomerOrderSummary customerOrderSummary = new CustomerOrderSummary();
            if (customerStatistic.getMonth().equals("2024-07")){
                List<CustomerOrderSummary> v23 = yy1KpiMapper.selectByAddressSearchTermAndCreationDate3(customerStatistic.getCustomerCode(), customerStatistic.getRecordTime());
                if (v23.size()!=1){
                    double i=0;
                    for (CustomerOrderSummary orderSummary : v23) {
                        i+=orderSummary.getFirstOrderMonthFY24_25();
                    }
                    customerOrderSummary.setFirstOrderMonthFY24_25(i);
                }else {
                    customerOrderSummary.setFirstOrderMonthFY24_25(v23.getFirst().getFirstOrderMonthFY24_25());
                }
                if (v23.getFirst().getBusiness().isEmpty()){
                    String chayewu = yy1KpiMapper.chayewu(customerStatistic.getCustomerCode());
                    customerOrderSummary.setBusiness(chayewu);
                }else {
                    customerOrderSummary.setBusiness(v23.getFirst().getBusiness());
                }

                Double v24 = yy1KpiMapper.SUMConditionAmount(customerStatistic.getCustomerCode());
                Double jine = yy1KpiMapper.selectByAddressSearchTermAndCreationDate2(customerStatistic.getCustomerCode(), "2024-07-01 00:00:00.000", "2024-08-01 00:00:00.000");
                if (v24==null){
                    customerOrderSummary.setCumulativeOrderFY24_25(jine);
                }else {
                    customerOrderSummary.setCumulativeOrderFY24_25(v24+jine);
                }
            }else {
                CustomerOrderSummary customerOrderSummaries1 = yy1KpiMapper.selectByAddressSearchTermAndCreationDate(customerStatistic.getCode(), customerStatistic.getRecordTime());
                customerOrderSummary.setFirstOrderMonthFY24_25(customerOrderSummaries1.getFirstOrderMonthFY24_25());
                customerOrderSummary.setBusiness(customerOrderSummaries1.getBusiness());
                Double v24 = yy1KpiMapper.SUMConditionAmount(customerStatistic.getCustomerCode());
                customerOrderSummary.setCumulativeOrderFY24_25(v24);
            }
            customerOrderSummary.setCustomerListLastYear(customerStatistic.getCustomerName());
            customerOrderSummary.setSalesDepartment(customerStatistic.getDepartmentName());
            customerOrderSummary.setMonth(customerStatistic.getMonth());
            customerOrderSummary.setCode(customerStatistic.getCode());
            customerOrderSummary.setDates(customerStatistic.getRecordTime());
            Double v23 = yy1KpiMapper.selectByAddressSearchTermAndCreationDate2(customerStatistic.getCustomerCode(), "2023-07-01 00:00:00.000", "2024-07-01 00:00:00.000");
            customerOrderSummary.setOrderAmountFY23_24(v23);
            customerOrderSummaries.add(customerOrderSummary);
        }
        customerOrderSummaryMapper.truncateTable();
        for (CustomerOrderSummary customerOrderSummary : customerOrderSummaries) {
            customerOrderSummaryMapper.insert(customerOrderSummary);
        }



        return "ddfdsf";
    }

}
